<?php

class Flexical_Widget extends WP_Widget
{
	// Actual widget processes
	public function Flexical_Widget()
	{
		parent::WP_Widget( false, 'Flexical' );
	}

	// Draws the widget admin form
	public function form( $instance )
	{
		extract( $instance );

		echo( '<p><label for="' . $this->get_field_id( 'title' ) . '">Title:</label>' );
		echo( '<input id="' . $this->get_field_id( 'title' ) . '" name="' . $this->get_field_name( 'title' ) . '" value="' . $instance[ 'title' ] . '" class="widefat" /></p>' );


		echo( '<p><label for="' . $this->get_field_id( 'listing_id' ) . '">Select Listing:</label>' );
		echo( '<select id="' . $this->get_field_id( 'listing_id' ) . '" name="' . $this->get_field_name( 'listing_id' ) . '" class="widefat" style="width:100%;">' );

		foreach ( $this->get_listings() as $listing )
		{
			echo( '<option value="' . $listing->id . '"' .
				( $listing->id == $instance[ 'listing_id' ] ? ' selected' : '' ) .
				'>' . $listing->title . '</option>' );
		}

		echo( '</select></p>' );
	}

	// Updates the widget settings
	public function update( $new_instance, $old_instance )
	{
		return $new_instance;
	}

	// Outputs the widget content
	public function widget( $args, $instance )
	{
		extract( $args );

		$listing_id = $instance[ 'listing_id' ];
		$listing = isset( $listing_id ) ? $this->get_listing( $listing_id ) : null;
		$title = $instance[ 'title' ];

		echo( $before_widget . $before_title . $title . $after_title );

		if ( empty( $listing ) )
		{
			echo( "<h2>Widget Configuration Error: No such listing with ID = " . $listing_id . "</h2>\n" );
		}

		else
		{
			require_once( 'flexical/service/report-generator.php' );
			$generator = new Flexical_Service_Report_Generator();
			echo( $generator->generate( $listing ) );
		}

		echo( $after_widget );
	}

	private function get_listing( $id = -1 )
	{
		require_once( 'flexical/service/dao.php' );
		$dao = new Flexical_Service_DAO();
		return $dao->read_listing( $id );
	}

	private function get_listings()
	{
		require_once( 'flexical/service/dao.php' );
		$dao = new Flexical_Service_DAO();
		return $dao->read_listings();
	}
}

?>
